from rest_framework import serializers
from .models import (
    Platform, Keyword, SentimentData, SentimentKeywordRelation,
    MonitorTarget, AlertRule, AlertLog, SystemStatus, DailyStatistics
)

class PlatformSerializer(serializers.ModelSerializer):
    class Meta:
        model = Platform
        fields = '__all__'

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ['id', 'word', 'weight', 'is_active', 'created_at', 'updated_at']

class SentimentKeywordRelationSerializer(serializers.ModelSerializer):
    keyword_name = serializers.CharField(source='keyword.word', read_only=True)
    
    class Meta:
        model = SentimentKeywordRelation
        fields = ['keyword', 'keyword_name', 'frequency']

class SentimentDataSerializer(serializers.ModelSerializer):
    platform_name = serializers.CharField(source='platform.name', read_only=True)
    platform_icon = serializers.CharField(source='platform.icon', read_only=True)
    sentiment_label = serializers.CharField(source='get_sentiment_type_display', read_only=True)
    keywords_data = SentimentKeywordRelationSerializer(source='sentimentkeywordrelation_set', many=True, read_only=True)
    
    class Meta:
        model = SentimentData
        fields = ['id', 'title', 'content', 'url', 'platform', 'platform_name', 'platform_icon',
                 'sentiment_value', 'sentiment_type', 'sentiment_label', 'heat_value',
                 'publish_time', 'created_at', 'keywords_data']

class SentimentDataBriefSerializer(serializers.ModelSerializer):
    """简要舆情数据序列化器，用于列表展示"""
    platform_name = serializers.CharField(source='platform.name', read_only=True)
    platform_icon = serializers.CharField(source='platform.icon', read_only=True)
    sentiment_label = serializers.CharField(source='get_sentiment_type_display', read_only=True)
    content_brief = serializers.SerializerMethodField()
    
    class Meta:
        model = SentimentData
        fields = ['id', 'title', 'content_brief', 'platform_name', 'platform_icon',
                 'sentiment_type', 'sentiment_label', 'heat_value', 'publish_time']
    
    def get_content_brief(self, obj):
        """获取内容摘要，截取前50个字符"""
        return obj.content[:50] + ('...' if len(obj.content) > 50 else '')

class MonitorTargetSerializer(serializers.ModelSerializer):
    keywords = KeywordSerializer(many=True, read_only=True)
    keyword_ids = serializers.PrimaryKeyRelatedField(
        many=True, 
        queryset=Keyword.objects.all(),
        source='keywords',
        required=False,
        write_only=True
    )
    
    type_display = serializers.SerializerMethodField()
    
    class Meta:
        model = MonitorTarget
        fields = [
            'id', 'name', 'type', 'type_display', 'image', 
            'description', 'is_priority', 'keywords', 'keyword_ids',
            'created_at', 'updated_at'
        ]
    
    def get_type_display(self, obj):
        type_map = {
            1: "企业",
            2: "人物",
            3: "事件",
            4: "其他"
        }
        return type_map.get(obj.type, str(obj.type))

class AlertRuleSerializer(serializers.ModelSerializer):
    target_name = serializers.CharField(source='target.name', read_only=True)
    
    class Meta:
        model = AlertRule
        fields = '__all__'

class AlertLogSerializer(serializers.ModelSerializer):
    rule_name = serializers.CharField(source='rule.name', read_only=True)
    target_name = serializers.CharField(source='rule.target.name', read_only=True)
    
    class Meta:
        model = AlertLog
        fields = '__all__'

class SystemStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemStatus
        fields = '__all__'

class DailyStatisticsSerializer(serializers.ModelSerializer):
    class Meta:
        model = DailyStatistics
        fields = '__all__'

# 首页数据概览序列化器
class HomeStatisticsSerializer(serializers.Serializer):
    # 实时数据总览
    today_total = serializers.IntegerField()  # 今日舆情总量
    realtime_increment = serializers.IntegerField()  # 实时新增舆情数量
    platform_count = serializers.IntegerField()  # 当前在线监测平台数
    
    # 情感分布
    sentiment_distribution = serializers.DictField()  # 正/负面舆情比例
    sentiment_trend = serializers.ListField()  # 情感趋势变化（近24小时）
    
    # 热点排名
    hot_keywords = serializers.ListField()  # 热门关键词Top10
    hot_sentiments = serializers.ListField()  # 热度最高舆情Top5
    
    # 舆情趋势图表
    platform_comparison = serializers.ListField()  # 分平台舆情数量对比
    sentiment_time_distribution = serializers.ListField()  # 情感值时间分布
    
    # 关键指标
    alert_count = serializers.IntegerField()  # 预警触发次数
    alert_increment = serializers.IntegerField()  # 较昨日增长百分比
    priority_targets = serializers.ListField()  # 重点监控对象
    extreme_sentiment = serializers.DictField()  # 情感极值
    
    # 系统状态
    system_status = serializers.DictField()  # 系统服务健康状态 